//
//  ConsultViewController.m
//  安好
//
//  Created by lianchuang on 14-11-5.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "ConsultViewController.h"
#import "ConsultView.h"
#import "DepartmentListViewController.h"
#import "ConsultDoctorsViewController.h"
#import "DocInfoViewController.h"
#import "AFURLSessionManager.h"
#import "ConsultingChatViewController.h"
#import "ChatContent.h"
#import "ConsultList.h"
#import "AppDelegate.h"
#import "MyConsultViewCell.h"
#import "ObtainQualificationsViewController.h"
#import "ConsultFamilyViewController.h"
#import "XHImageViewer.h"
#import "UIView+XHRemoteImage.h"
@interface ConsultViewController ()<SelectDepartment,UIAlertViewDelegate,DocInfoDelegate,UIActionSheetDelegate,XHImageViewerDelegate,UITextFieldDelegate,UINavigationControllerDelegate>

@end

@implementation ConsultViewController
{
    ConsultView *ImgTextConsult;
    //存取图片个数
    NSMutableArray *imageArrays;
    //存取删除图片上button个数
    NSMutableArray *buttonArrays;
    //存取图片的url
    NSMutableArray *imageURlArrays;
    NSMutableArray *halfImageURL;
    //男女按钮
    QRadioButton *_radio1;
    QRadioButton *_radio2;
    NSDictionary *familyDic;
    NSInteger picCount;
    UIButton *rightBtn;
}
@synthesize myInfoDic;
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self getMyInfoAndResetUI];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [ImgTextConsult.descriptionTextview resignFirstResponder];
    [super viewWillDisappear:animated];
}
- (void)getMyInfoAndResetUI
{
    if (!myInfoDic||myInfoDic.count<=0) {
        UserModel *userModel = [[UserManager shareInstance]getUserInfo];
        NSString *uid=userModel.uid;
        NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
        NSString *name= [userdefault valueForKey:[NSString stringWithFormat:@"%@realname",userModel.uid]];

        NSString *age=[NSString stringWithFormat:@"%@",[userdefault valueForKey:[NSString stringWithFormat:@"%@age",userModel.uid]]];
        NSString *gender=[NSString stringWithFormat:@"%@",[userdefault valueForKey:[NSString stringWithFormat:@"%@gender",uid]]
                          ];
        familyDic=@{
                    @"fid": @"0",//(家人id)
                    @"gender": gender,//(性别 0:保密 1:男 2:女)
                    @"type": @"0",//(关系id)
                    @"realname":name,//(家人姓名)
                    @"age": age,//(年龄 -1:未填写)
                    @"relation": @"我",//(关系)
                    @"mobile":[userdefault valueForKey:[NSString stringWithFormat:@"%@mobile",uid]]
                    };
        ImgTextConsult.fanmilyMember.text=[NSString stringWithFormat:@"%@（%@）",name,[familyDic valueForKey:@"relation"]];
        if ([age isEqualToString:@"-1"]||[age isEqualToString:@"0"]||[age intValue]<=0) {
            ImgTextConsult.Age.userInteractionEnabled=YES;
        }else
        {
            ImgTextConsult.Age.text=age;
            ImgTextConsult.Age.userInteractionEnabled=NO;
        }
        if ([gender isEqualToString:@"1"]) {
            [_radio1 setChecked:YES];
            _radio1.userInteractionEnabled=NO;
            _radio2.userInteractionEnabled=NO;
        }else if ([gender isEqualToString:@"2"])
        {
            [_radio2 setChecked:YES];
            _radio1.userInteractionEnabled=NO;
            _radio2.userInteractionEnabled=NO;
        }else
        {
            [_radio1 setChecked:NO];
            [_radio2 setChecked:NO];
            _radio1.userInteractionEnabled=YES;
            _radio2.userInteractionEnabled=YES;
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *userDefult=[NSUserDefaults standardUserDefaults];
    if ([[userDefult objectForKey:@"archives"] isEqualToString:@"1"]&&[[userDefult objectForKey:@"invite"] isEqualToString:@"1"]) {
        //已获取指定医生资格（——————>医生列表页）
        if ([self.docInfo count]>0) {
            ImgTextConsult.doctorName.text=[self.docInfo valueForKey:@"username"];
            if (![[self.docInfo valueForKey:@"username"] isEqualToString:@"不指定医生"]) {
                ImgTextConsult.departmentName.text=[self.docInfo valueForKey:@"departmentname"];
            }
        }
    }
    else {
        //未获取指定医生资格（——————>获取资格页）
        if ([self.docInfo count]>0) {
            if (![[self.docInfo valueForKey:@"username"] isEqualToString:@"不指定医生"]) {
                ImgTextConsult.departmentName.text=[self.docInfo valueForKey:@"departmentname"];
            }
        }
    }
    picCount=0;
    UIViewController *conVC=[[[self.tabBarController.viewControllers objectAtIndex:1] viewControllers]objectAtIndex:0];
    if ([conVC isEqual:self]) {
    }else
    {
//        if ([self.isFromAnhao isEqualToString:@"1"]) {
            UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
            backImg.tintColor = [UIColor whiteColor];
            self.navigationItem.leftBarButtonItem = backImg;
//        }
    }
    [self.navigationController.navigationBar setBarTintColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16]];
    //nav半透明设置
//    self.navigationController.navigationBar.translucent=NO;
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"图文咨询",@"视频咨询",nil];
    rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    rightBtn.frame=CGRectMake(0, 0, 30, 30);
    [rightBtn addTarget:self action:@selector(selectSubmit) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"提交" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    //暂时显示title
    self.navigationItem.title=@"咨询医生";
    //初始化UISegmentedControl
    self.segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    [self.segmentedControl addTarget:self action:@selector(segmentedControlClick:) forControlEvents:UIControlEventValueChanged];
    self.segmentedControl.frame = CGRectMake(0.0, 10.0, 150.0, 24.0);
    self.segmentedControl.selectedSegmentIndex = 0;//设置默认选择项索引
    self.segmentedControl.layer.masksToBounds = YES;
    self.segmentedControl.layer.cornerRadius = 4.0;
    self.segmentedControl.layer.borderWidth = 1.0;
    self.segmentedControl.backgroundColor=[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    self.segmentedControl.layer.borderColor =[[UIColor colorWithRed:1 green:1 blue:1 alpha:0.9] CGColor];
    self. segmentedControl.tintColor =[UIColor colorWithRed:1 green:1 blue:1 alpha:0.9];
    //暂时隐藏segment
//    self.navigationItem.titleView = self.segmentedControl;
    self.consultType=@"0";
    buttonArrays=[[NSMutableArray alloc]init];
    imageArrays=[[NSMutableArray alloc]init];
    imageURlArrays=[[NSMutableArray alloc]init];
    halfImageURL=[[NSMutableArray alloc]init];
    [self initWithScrollView];
    self.dataArray=[[NSMutableArray alloc]init];
    [self initWithConsultList];
    if (self.docInfo) {
        NSUserDefaults *userDefult=[NSUserDefaults standardUserDefaults];
        if ([[userDefult objectForKey:@"archives"] isEqualToString:@"1"]&&[[userDefult objectForKey:@"invite"] isEqualToString:@"1"]) {
            //已获取指定医生资格（——————>医生列表页）
            ImgTextConsult.doctorName.text=[self.docInfo valueForKey:@"username"];
            ImgTextConsult.departmentName.text=[self.docInfo valueForKey:@"departmentname"];
        }
        else {
            //未获取指定医生资格（——————>获取资格页）
            ImgTextConsult.departmentName.text=[self.docInfo valueForKey:@"departmentname"];
        }
    }else
    {
        self.docInfo=[[NSDictionary alloc]init];
    }
    self.departmentInfo=[[NSDictionary alloc]init];
    familyDic=[[NSDictionary alloc]init];
    myInfoDic=[[NSDictionary alloc]init];
}

- (void)initWithConsultList
{
//    if (kScreenWidth==414) {
//        self.consultList=[[[NSBundle mainBundle] loadNibNamed:@"ConsultListView" owner:self options:nil] lastObject];
//    }else{
//        self.consultList=[[[NSBundle mainBundle] loadNibNamed:@"ConsultListView" owner:self options:nil] objectAtIndex:0];
//    }
//    self.consultList.frame=CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight);
//    [self.view addSubview:self.consultList];
}
-(void)initWithScrollView{
//    self.mainView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
//    self.mainView.directionalLockEnabled = YES;
//    self.mainView.pagingEnabled = NO;
//    self.mainView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
//    self.mainView.showsVerticalScrollIndicator = NO;
//    self.mainView.showsHorizontalScrollIndicator = NO;
//    self.mainView.delegate = self;
//    CGSize newSize = CGSizeMake(0,  kScreenHeight+150);
//    [self.mainView setContentSize:newSize];
    
    //图文咨询
    if (kScreenWidth==414) {
        ImgTextConsult=[[[NSBundle mainBundle]loadNibNamed:@"ConsultView" owner:self options:nil] lastObject];

    }else{
        ImgTextConsult=[[[NSBundle mainBundle]loadNibNamed:@"ConsultView" owner:self options:nil] objectAtIndex:0];

    }
    ImgTextConsult.departmentDelegate=self;
    
    ImgTextConsult.frame=CGRectMake(0, 0, kScreenWidth,CGRectGetHeight(self.view.frame));
    ImgTextConsult.addphoto.hidden=YES;
    ImgTextConsult.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:ImgTextConsult];
    ImgTextConsult.descriptionTextview.delegate=self;
    ImgTextConsult.Age.delegate=self;
    ImgTextConsult.Age.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    [self autosizeFontAndSize:ImgTextConsult.labeltext withText:ImgTextConsult.labeltext.text];
    _radio1 = [[QRadioButton alloc] initWithDelegate:self groupId:@"groupId1"];
    if (kScreenWidth==414) {
        _radio1.frame = CGRectMake(kScreenWidth-150, 4, 48, 48);

    }else{
        _radio1.frame = CGRectMake(kScreenWidth-120, 2, 40, 40);

    }
    [_radio1 setTitle:@"男" forState:UIControlStateNormal];
    [_radio1 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_radio1.titleLabel setFont:[UIFont boldSystemFontOfSize:LABEL_FONT_SIZE_CONTENT_13]];
    [ImgTextConsult.sexView addSubview:_radio1];
//    [_radio1 setChecked:YES];
    
    _radio2 = [[QRadioButton alloc] initWithDelegate:self groupId:@"groupId1"];
    if (kScreenWidth==414) {
        _radio2.frame = CGRectMake(kScreenWidth-80, 4, 48, 48);

    }else{
        _radio2.frame = CGRectMake(kScreenWidth-70, 2, 40, 40);

    }
    [_radio2 setTitle:@"女" forState:UIControlStateNormal];
    [_radio2 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_radio2.titleLabel setFont:[UIFont boldSystemFontOfSize:LABEL_FONT_SIZE_CONTENT_13]];
    [ImgTextConsult.sexView addSubview:_radio2];

    
    
    
    //视频咨询
    ConsultView *VidioConsult=[[[NSBundle mainBundle]loadNibNamed:@"ConsultView" owner:self options:nil] lastObject];
    VidioConsult.frame=CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight);
    VidioConsult.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:VidioConsult];
    
}
#pragma mark - QRadioButtonDelegate

- (void)didSelectedRadioButton:(QRadioButton *)radio groupId:(NSString *)groupId {
//    NSLog(@"did selected radio:%@ groupId:%@", radio.titleLabel.text, groupId);
    NSString *gender;
    if ([radio.titleLabel.text isEqualToString:@"男"]) {
        gender=@"1";
    }else if ([radio.titleLabel.text isEqualToString:@"女"])
    {
        gender=@"2";
    }
    else
    {
        gender=@"0";
    }
    UserModel *userModel = [[UserManager shareInstance]getUserInfo];
    NSString *uid=userModel.uid;
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    [userdefault setValue:gender forKey:[NSString stringWithFormat:@"%@gender",uid]];
}

-(IBAction)segmentedControlClick:(id)sender{
    switch (self.segmentedControl.selectedSegmentIndex) {
        case 0:
        {
            self.consultType=@"0";
//            [self.mainView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        break;
        case 1:
        {
            self.consultType=@"1";
//            [self.mainView setContentOffset:CGPointMake(kScreenWidth, 0) animated:YES];
        }
        break;
        default:
        break;
    }

}
#pragma mark UIScrollView代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    int index = fabs(scrollView.contentOffset.x) / scrollView.frame.size.width;
    self.segmentedControl.selectedSegmentIndex = index;
    //    [self.switcher forceSelectedIndex:index animated:YES];
    //index为当前页码
}
#pragma  mark SelectDepartmentsDelegate  选择按钮代理方法
- (void)doFamily
{
    ConsultFamilyViewController *consultFamily=[[ConsultFamilyViewController alloc]initWithNibName:@"ConsultFamilyViewController" bundle:[NSBundle mainBundle]];
    consultFamily.fid=@"0";
    if (familyDic&&familyDic.count>0) {
        consultFamily.fid=[NSString stringWithFormat:@"%@",[familyDic valueForKey:@"fid"]];
    }
    [consultFamily returnFamData:^(NSDictionary *dict) {
        MyNSLog("%@", dict);
        familyDic=dict;
        myInfoDic=dict;
        ImgTextConsult.fanmilyMember.text=[NSString stringWithFormat:@"%@ （%@）",[dict valueForKey:@"realname"],[dict valueForKey:@"relation"]];
        NSString *age=[NSString stringWithFormat:@"%@",[dict valueForKey:@"age"]];
        if ([age intValue]>0){
            ImgTextConsult.Age.text=[dict valueForKey:@"age"];
            ImgTextConsult.Age.userInteractionEnabled=NO;
        }else
        {
            ImgTextConsult.Age.text=@"";
            ImgTextConsult.Age.userInteractionEnabled=YES;
        }
        _radio1.checked=NO;
        _radio2.checked=NO;
        NSString *gender=[NSString stringWithFormat:@"%@",[dict valueForKey:@"gender"]];
        if ([gender isEqual:@"0"]) {
            _radio1.userInteractionEnabled=YES;
            _radio2.userInteractionEnabled=YES;
        }else if ([gender isEqualToString:@"1"])
        {
            [_radio1 setChecked:YES];
            _radio1.userInteractionEnabled=NO;
            _radio2.userInteractionEnabled=NO;
        }
        else if ([gender isEqualToString:@"2"])
        {
            [_radio2 setChecked:YES];
            _radio1.userInteractionEnabled=NO;
            _radio2.userInteractionEnabled=NO;
        }
        
        if ([[dict valueForKey:@"mobile"] length]>0) {
            self.mobile=[dict valueForKey:@"mobile"];
        }else
        {
            self.mobile=@"";
        }
    }];
    [self.navigationController pushViewController:consultFamily animated:YES];
}
- (void)doDepartments
{
    DepartmentListViewController *departmentList=[[DepartmentListViewController alloc]initWithNibName:@"DepartmentListViewController" bundle:[NSBundle mainBundle]];
    departmentList.sel_count=@"0";
    if ([self.departmentInfo count]>0) {
        departmentList.sel_count=[NSString stringWithFormat:@"%@",[self.departmentInfo valueForKey:@"departmentid"]];
    }
    if (self.docInfo.count>0) {
        departmentList.sel_count=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"departmentid"]];
    }
    [departmentList returnDepartmentName:^(NSDictionary *dict) {
        ImgTextConsult.departmentName.text=[dict valueForKey:@"departmentname"];
        ImgTextConsult.doctorName.text=@"不指定医生";
        self.docInfo=nil;
        self.departmentInfo=dict;
    }];
    [self.navigationController pushViewController:departmentList animated:YES];
}
- (void)doCamera
{
//    alertContent(nil);
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
    [alert show];
}
- (void)addphotos
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
    [alert show];
}
- (void)doDoctors
{
    NSUserDefaults *userDefult=[NSUserDefaults standardUserDefaults];
    if ([[userDefult objectForKey:@"archives"] isEqualToString:@"1"]&&[[userDefult objectForKey:@"invite"] isEqualToString:@"1"]) {
        //已获取指定医生资格（——————>医生列表页）
        if ([self.consultType isEqualToString:@"0"]) {
            ConsultDoctorsViewController *consultDoc=[[ConsultDoctorsViewController alloc]initWithNibName:@"ConsultDoctorsViewController" bundle:[NSBundle mainBundle]];
            consultDoc.uid=@"0";
            if (self.docInfo&&self.docInfo.count>0) {
                consultDoc.uid=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"uid"]];
            }
            [consultDoc returnDocData:^(NSDictionary *dict) {
                MyNSLog("%@",dict);
            ImgTextConsult.doctorName.text=[dict valueForKey:@"username"];
            if (![[dict valueForKey:@"username"] isEqualToString:@"不指定医生"]) {
                ImgTextConsult.departmentName.text=[dict valueForKey:@"departmentname"];
                self.departmentInfo=nil;
            }else{
                ImgTextConsult.departmentName.text=@"不指定科室";
            }
            self.docInfo=dict;
            }];
            if ([self.departmentInfo valueForKey:@"departmentid"]) {
                consultDoc.departmentId=[self.departmentInfo valueForKey:@"departmentid"];
            }else
            {
                consultDoc.departmentId=@"0";
            }
            [self.navigationController pushViewController:consultDoc animated:YES];
        }else
        {
//            [self.navigationController pushViewController:[VideoListViewController instance] animated:YES];
        }
    }
    else {
        //未获取指定医生资格（——————>获取资格页）
        ObtainQualificationsViewController *obtain;
        if (kScreenWidth==414) {
            obtain=[[ObtainQualificationsViewController alloc] initWithNibName:@"ObtainQualificationsViewController6+" bundle:[NSBundle mainBundle]];
        }
        else{
            obtain=[[ObtainQualificationsViewController alloc] initWithNibName:@"ObtainQualificationsViewController" bundle:[NSBundle mainBundle]];
        }
        obtain.departmentId=[self.departmentInfo valueForKey:@"departmentid"];
        obtain.consult=self;
        [self.navigationController pushViewController:obtain animated:YES];
    }
}
- (void)selectSubmit
{
    if (![self JudgeSubmitText]) {
        return;
    }
    rightBtn.userInteractionEnabled=NO;
    [self showActionView];
    [ImgTextConsult.descriptionTextview resignFirstResponder];
    [ImgTextConsult.Age resignFirstResponder];
    ImgTextConsult.submit.userInteractionEnabled=NO;
    NSString * postURL = [NSString stringWithFormat:@"%@question/add/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //判断个人信息
    NSMutableString *multString=[[NSMutableString alloc]init];
    if (halfImageURL.count>0) {
        for (int i=0; i<halfImageURL.count; i++) {
            if (i==0) {
                [multString appendString:[halfImageURL objectAtIndex:i]];
            }else
            {
                [multString appendString:[NSString stringWithFormat:@",%@",[halfImageURL objectAtIndex:i]]];
            }
        }
    }
    else
    {
        NSString *str=@"";
        multString=[NSMutableString stringWithString:str];
    }
    NSString *age;
    if ([[familyDic valueForKey:@"age"] isEqual:@"-1"]||[[familyDic valueForKey:@"age"] isEqual:@"0"]) {
        age=ImgTextConsult.Age.text;
        NSString *fid=[NSString stringWithFormat:@"%@",[familyDic valueForKey:@"fid"]];
        if ([fid isEqualToString:@"0"]) {
            UserModel *userModel = [[UserManager shareInstance]getUserInfo];
            NSString *uid=userModel.uid;
            NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
            [userdefault setValue:age forKey:[NSString stringWithFormat:@"%@age",uid]];
            [userdefault synchronize];
        }
    }else
    {
        age=ImgTextConsult.Age.text;
    }
    
    NSString *fid;
    NSString *name;
    NSString *mobile;
    if ([familyDic count]<=0) {
        fid=@"0";
        UserModel * userModel = [[UserManager shareInstance]getUserInfo];
        name= [[NSUserDefaults standardUserDefaults]valueForKey:[NSString stringWithFormat:@"%@realname",userModel.uid]];
        mobile=@"";
    }else
    {
        fid=[familyDic valueForKey:@"fid"];
        name=[familyDic valueForKey:@"realname"];
        mobile=[familyDic valueForKey:@"mobile"];
    }
    NSString *gender;
    if (_radio1.checked) {
        gender=@"1";
    }else if(_radio2.checked)
    {
        gender=@"2";
    }
    //判断医生或者科室信息
    NSString *docid;
    NSString *doclevel;
    NSString *depart;
    NSString *docname;
    NSString *departname;
    //指定(不确定科室)
    if (self.docInfo.count>0&&![[self.docInfo valueForKey:@"username"] isEqualToString:@"不指定医生"]) {
        NSUserDefaults *userDefult=[NSUserDefaults standardUserDefaults];
        if ([[userDefult objectForKey:@"archives"] isEqualToString:@"1"]&&[[userDefult objectForKey:@"invite"] isEqualToString:@"1"]) {
            docid=[NSString stringWithFormat:@"%@",[self.docInfo objectForKey:@"uid"]];
            doclevel=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"doclevelid"]];
        }else
        {
            docid=@"0";
            doclevel=@"0";
        }
        depart=[self.docInfo valueForKey:@"departmentid"];
        docname=[self.docInfo valueForKey:@"username"];
        departname=[self.docInfo valueForKey:@"departmentname"];
    }
    else //未指定
    {
        docid=@"0";
        doclevel=@"0";
        docname=@"";
        if (self.departmentInfo&&[self.departmentInfo count]>0) {
            depart=[self.departmentInfo valueForKey:@"departmentid"];
            departname=[self.departmentInfo valueForKey:@"departmentname"];
        }else{
            depart=@"0";
            departname=@"不确定科室";
        }
    }
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"departmentid":[NSString stringWithFormat:@"%@",depart],
                                 @"doctoruid":docid,
                                 @"message":ImgTextConsult.descriptionTextview.text,
                                 @"departmentname":departname,
                                 @"pic":multString,
                                 @"age":age,
                                 @"gender":gender,
                                 @"fid":fid,
                                 @"patient":name,
                                 @"mobile":mobile,
                                 @"doctorname":docname,
                                 @"doclevelid":doclevel,
                                 };
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        rightBtn.userInteractionEnabled=YES;
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        NSDictionary *dict=[responseObject valueForKey:@"data"];
        if ([statusString isEqualToString:@"0"]) {
            [self hiddenActionView];
        }
        else{
            ConsultingChatViewController * consultingViewController = [[ConsultingChatViewController alloc]init];
            consultingViewController.qid = [dict objectForKey:@"qid"];
            //指定还是未指定？

            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *dateline = dateString;
            
//            NSString *depart;
//            if (ImgTextConsult.departmentName.text.length<=0) {
//                depart=@"不确定科室";
//            }else
//            {
//                if([ImgTextConsult.departmentName.text isEqualToString:@"选择科室"])
//                {
//                    depart=@"不确定科室";
//                }else
//                {
//                    depart=ImgTextConsult.departmentName.text;
//                }
//            }
            //指定医生
            if (![docid isEqualToString:@"0"]&&![docid isEqual:[NSNull null]]) {
                consultingViewController.userName =docname;
                consultingViewController.ConsultDic=@{
                                                      @"consultType":@"1",
                                                      @"dateline":dateline,
                                                      @"doctorname":docname,
                                                      @"departmentname":departname,
                                                      @"content":ImgTextConsult.descriptionTextview.text,
                                                      @"follow":[dict valueForKey:@"follow"],
                                                      @"pic":multString,
                                                      @"picurl":[self.docInfo valueForKey:@"avatar"],
                                                      @"relation":[dict valueForKey:@"relation"],
                                                      @"doctoruid":docid,
                                                      @"hight_keywords":[dict valueForKey:@"hight_keywords"],
                                                      };
                consultingViewController.toMed = @"3";
                consultingViewController.isAssin=YES;
            }
            //未指定医生
            else
            {
                consultingViewController.isAssin=NO;
                consultingViewController.userName=@"";
                consultingViewController.ConsultDic=@{
                                                      @"consultType":@"1",
                                                      @"dateline":dateline,
                                                      @"departmentname":departname,
                                                      @"content":ImgTextConsult.descriptionTextview.text,
                                                      @"pic":multString,
                                                      @"relation":[dict valueForKey:@"relation"],
                                                      @"tips":[dict valueForKey:@"tips"],
                                                      @"doctor_count":[dict valueForKey:@"doctor_count"],
                                                      @"hight_keywords":[dict valueForKey:@"hight_keywords"],
                                                      };
                consultingViewController.toMed = @"";
            }
            consultingViewController.isFromwhere = 1;
            consultingViewController.toTpye = @"2";
            consultingViewController.isFromConsult=YES;
            consultingViewController.consultType=self.consultType;
            NSString *pic=[NSString stringWithFormat:@"%@",multString];
            NSString *info=ImgTextConsult.descriptionTextview.text;
            dispatch_queue_t queue = dispatch_get_main_queue();
            dispatch_async(queue, ^{
                NSDictionary *dicM=[[NSDictionary alloc]initWithObjectsAndKeys:[dict objectForKey:@"qid"],@"qid",docid,@"uid",[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]],@"dateline",info,@"message",pic,@"pic",@"",@"type",@"",@"action",consultingViewController.userName,@"username",@"",@"voice",@"",@"voicelength",@"1",@"isQuestion",@"",@"method",@"1",@"success",departname,@"departmentname",self.consultType,@"consultType",nil];
                NSString *mess=[YXJSON JSONStringWithDictionaryOrArray:dicM];
                [ConsultList updateConsultList:mess withReadStatus:@"-1" withSuccess:@"1" withMessageDirection:@"1"];
            });
            UserModel * userModel = [[UserManager shareInstance]getUserInfo];
            NSString * name= userModel.username;
            NSString *myuid=userModel.uid;
            NSString * string = [NSString stringWithFormat:@"%@指定您一个问题",name];
            NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action",myuid , @"from_uid", @"1", @"from_type",@"2", @"to_type", docid, @"to_uid", string, @"message", [dict objectForKey:@"qid"], @"qid", consultingViewController.toMed, @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
            if ([docid isEqualToString:@"0"]) {
            }
            else
            {
                AppDelegate *del = (AppDelegate *)[UIApplication sharedApplication].delegate;
                NSString *jsonString = [dictionary JSONString];
                @try {
                    if (del.webSocket.readyState == 1) {
                        [del.webSocket send:jsonString];
                    } else {
                        AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                        [app webSocket];
                    }
                }
                @catch (NSException *exception) {
                    MyNSLog("exception = %@", exception);
                }
            }
            
            [self.navigationController pushViewController:consultingViewController animated:YES];

            [self clearInfo];
            [self getMyInfoAndResetUI];
            [self hiddenActionView];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        rightBtn.userInteractionEnabled=YES;
        [self hiddenActionView];
        [self clearInfo];
        [self getMyInfoAndResetUI];
        [self showCustomHudSingleLine:@"提交失败"];
    }];
}
/**
 *      //清空数据
 */
- (void)clearInfo
{
    myInfoDic=nil;
    familyDic=nil;
//    [VideoListViewController instance].docdic=nil;
    self.docInfo=nil;
    picCount=0;
    self.departmentInfo=nil;
    ImgTextConsult.departmentName.text=@"不指定科室";
    ImgTextConsult.descriptionTextview.text=@"";
    ImgTextConsult.doctorName.text=@"不指定医生";
    ImgTextConsult.Age.text=@"";
    for (int i=0; i<imageArrays.count; i++) {
        UIImageView *image=[imageArrays objectAtIndex:i];
        [image removeFromSuperview];
        
        UIButton *button=(UIButton *)[buttonArrays objectAtIndex:i];
        [button removeFromSuperview];
    }
    [imageArrays removeAllObjects];
    [imageURlArrays removeAllObjects];
    [halfImageURL removeAllObjects];
    [buttonArrays removeAllObjects];
    ImgTextConsult.labeltext.hidden=NO;
    ImgTextConsult.addphoto.hidden=YES;
}

/**
 *  判断提交的内容合不合法
*/
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd] &&([string intValue]>0&&[string intValue]<120);
}
- (BOOL)JudgeSubmitText
{
    
    if (ImgTextConsult.Age.text.length<=0) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写年龄" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }else if(![self isPureInt:ImgTextConsult.Age.text])
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写合法年龄(纯数字1-119岁)" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    if (!_radio1.checked&&!_radio2.checked) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择性别" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    if (ImgTextConsult.descriptionTextview.text.length<=0) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写症状描述" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }else if (ImgTextConsult.descriptionTextview.text.length>140){
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"症状描述多于140字，请简化描述后再提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }else if (ImgTextConsult.descriptionTextview.text.length<5){
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"症状描述少于10字，请详细描述后再提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    return YES;
}
#pragma mark AlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
            pickerImage.delegate=self;
            pickerImage.allowsEditing=YES;
            //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
            pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
            [self presentViewController:pickerImage animated:YES completion:nil];
        }
        else{
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
        }
        
    }
    else if(buttonIndex==2)
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
            pickerImage.delegate=self;
            NSArray * array1=[NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
            pickerImage.mediaTypes=array1;
            pickerImage.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.allowsEditing=YES;
            [self presentViewController:pickerImage animated:YES completion:nil];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}
#pragma mark ImagepickviewcontrollerDelegate 选择图片后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]) {
        [self postImage:info];
        [picker dismissViewControllerAnimated:YES completion:^{
        }]; 
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
}
/**
 *  上传图片
 *
 *  @param dic 图片的信息
 */
- (void)postImage:(NSDictionary *)dic
{
    [self showActionView];
    UIImage *postImage = [dic objectForKey:UIImagePickerControllerEditedImage];
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@thread/uploadpic/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [self hiddenActionView];
        if (error) {
            MyNSLog("Error: %@", error);
        } else {
            //图片上传成功
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                [halfImageURL addObject:[[responseObject valueForKey:@"data"] valueForKey:@"pic"]];
                [imageURlArrays addObject:[[responseObject valueForKey:@"data"] valueForKey:@"url"]];
                
                UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(15+(55+(kScreenWidth-55*4-30)/3)*imageArrays.count, 0, 55, 55)];
                imageView.image=postImage;
                imageView.tag=imageArrays.count+3000;
                imageView.layer.cornerRadius=3;
                imageView.layer.masksToBounds=YES;
                //在imageview上的button（用于删除）
                UIButton *imageButton=[UIButton buttonWithType:UIButtonTypeCustom];
                imageButton.frame=CGRectMake(15+(55+(kScreenWidth-55*4-30)/3)*imageArrays.count, 0, 55, 55);
                [imageButton addTarget:self action:@selector(dodelete:) forControlEvents:UIControlEventTouchUpInside];
                imageButton.tag=imageArrays.count;
                [imageArrays addObject:imageView];
                [buttonArrays addObject:imageButton];
                if (imageArrays.count>=1) {
                    ImgTextConsult.addphoto.frame=CGRectMake(15+(55+(kScreenWidth-55*4-30)/3)*imageArrays.count, 0, 55, 55);
                    ImgTextConsult.addphoto.hidden=NO;
                }
                [ImgTextConsult.imageBG addSubview:imageView];
                [ImgTextConsult.imageBG addSubview:imageButton];
            }else
            {
            }
        }
    }];
     [uploadTask resume];
}
/**
 *  删除上传的图片
 *
 *  @param sender 点击的当前的button
 */
- (void)dodelete:(UIButton *)sender
{
    /**
     *  暂时先不删除屏蔽内容，后边可能修改删除图片的url
     */
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    NSString *URLString=[NSString stringWithFormat:@"%@@thread/delpic/",kBaseURL];
//    NSDictionary *parameters = @{@"verson": kVersion,@"platform":kPlatform,@"picurl":[imageURlArrays objectAtIndex:sender.tag]};
//    [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        MyNSLog("JSON: %@", responseObject);
//        
//        NSString *status=[responseObject valueForKey:@"status"];
//        if ([status isEqualToString:@"1"]) {
//        }
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        MyNSLog("Error: %@", error);
//    }];
    picCount=sender.tag;
    UIActionSheet *actSheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"查看大图" otherButtonTitles:@"删除", nil];
    [actSheet showInView:[[[UIApplication sharedApplication] delegate] window]];
}
#pragma  mark UITetFeild Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    NSString *fid=[NSString stringWithFormat:@"%@",[familyDic valueForKey:@"fid"]];
    if ([fid isEqualToString:@"0"]) {
        UserModel *userModel = [[UserManager shareInstance]getUserInfo];
        NSString *uid=userModel.uid;
        NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
        [userdefault setValue:textField.text forKey:[NSString stringWithFormat:@"%@age",uid]];
        [userdefault synchronize];

    }
    
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *fid=[NSString stringWithFormat:@"%@",[familyDic valueForKey:@"fid"]];
    if ([fid isEqualToString:@"0"]) {
        
        if([self isPureInt:ImgTextConsult.Age.text])
        {
            UserModel *userModel = [[UserManager shareInstance]getUserInfo];
            NSString *uid=userModel.uid;
            NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
            [userdefault setValue:textField.text forKey:[NSString stringWithFormat:@"%@age",uid]];
            [userdefault synchronize];
        }
        

    }
}
#pragma mark UITextViewDelegate textView的代理方法
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    ImgTextConsult.labeltext.hidden=YES;//隐藏文字
    if (kScreenHeight==480) {
        [UIView animateWithDuration:0.3 animations:^{
            self.view.frame=CGRectMake(0, 10, self.view.frame.size.width, self.view.frame.size.height+150);
        }];
    }
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length>0) {
        ImgTextConsult.labeltext.hidden=YES;
        
    }else{
        ImgTextConsult.labeltext.hidden=NO;//隐藏文字
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        if (kScreenHeight==480) {
            [UIView animateWithDuration:0.15 animations:^{
                self.view.frame=CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-150);
            }];
        }
        [textView resignFirstResponder];
        return NO;
    }
    if (textView.text.length==0){//textview长度为0
        if ([text isEqualToString:@""]) {//判断是否为删除键
            ImgTextConsult.labeltext.hidden=YES;//隐藏文字
        }else{
            ImgTextConsult.labeltext.hidden=YES;
        }
    }else{//textview长度不为0
        if (textView.text.length==1){//textview长度为1时候
            if ([text isEqualToString:@""]) {//判断是否为删除键
                ImgTextConsult.labeltext.hidden=NO;
            }else{//不是删除
                ImgTextConsult.labeltext.hidden=YES;
            }
        }else{//长度不为1时候
            ImgTextConsult.labeltext.hidden=YES;
        }
    }
    return YES;
}
#pragma mark  ReturnDocInfo代理 返回医生详情信息.
- (void)returnDocInfo:(NSDictionary *)doc
{
    self.docInfo=doc;
    ImgTextConsult.doctorName.text=[self.docInfo valueForKey:@"username"];
    ImgTextConsult.departmentName.text=[self.docInfo valueForKey:@"departmentname"];
}
#pragma  mark 调整行间距和label自适应
- (void)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    label.attributedText = attributedString;
    [label sizeToFit];
}
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
//        int count = [imageArrays count];
        XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
        imageViewer.delegate = self;
        [imageViewer showWithImageViews:imageArrays selectedView:(UIImageView *)[self.view viewWithTag:picCount+3000]];
        
    }else if (buttonIndex==1)
    {  
        //删除UI上的控件（imageview和button）
        [[imageArrays objectAtIndex:picCount] removeFromSuperview];
        [[buttonArrays objectAtIndex:picCount] removeFromSuperview];
        //删除数组的值
        [imageArrays removeObjectAtIndex:picCount];
        [buttonArrays removeObjectAtIndex:picCount];
        [imageURlArrays removeObjectAtIndex:picCount];
        [halfImageURL removeObjectAtIndex:picCount];
        
        for (int i=0; i<imageArrays.count; i++) {
            [[imageArrays objectAtIndex:i] setFrame:CGRectMake(15+i*78, 0, 55, 55)];
            [[buttonArrays objectAtIndex:i] setFrame:CGRectMake(15+i*78, 0, 55, 55)];
            [((UIButton *)[buttonArrays objectAtIndex:i])setTag:i];
        }
        ImgTextConsult.addphoto.frame=CGRectMake(15 +[imageArrays count] * 78, 0, 55, 55);
        if (imageArrays.count<1) {
            ImgTextConsult.addphoto.hidden=YES;
        }

    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
